package haltica.com.mx.ape.web;

import flexjson.JSONSerializer;
import haltica.com.mx.ape.domain.Cliente;
import haltica.com.mx.ape.domain.Sucursal;
import haltica.com.mx.ape.domain.UserDetailsImpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RooWebScaffold(path = "sucursals", formBackingObject = Sucursal.class)
@RequestMapping("/sucursals")
@Controller
public class SucursalController {
	
	/**
	 * 
	 * @return
	 */
	@RequestMapping(value = "/listSucPerm", method = RequestMethod.GET)
	public ResponseEntity<String> listSucPerm() {
		
		UserDetailsImpl userDetails;
		List<Sucursal> listSuc = new ArrayList<Sucursal>();
		HttpHeaders headers;
		GenericResponse gRes;
		String json;
		ResponseEntity<String> response;
				
		userDetails = (UserDetailsImpl) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		
		if(userDetails.getAuthorities().contains(UsuarioSistemaController.ROLE_ADMIN)){
			listSuc = Sucursal.findAllSucursals();
		}
		
		if (userDetails.getAuthorities().contains(UsuarioSistemaController.ROLE_CLIENTE)) {
			listSuc = Sucursal.findSucursalesByIdCliente(Cliente.findCliente(userDetails.getDetails().getIdCliente()));
		}
		
		
		headers = new HttpHeaders();
		headers.set("Content-Type", "application/json");
		headers.add("Content-Type", "application/text; charset=utf-8");
		
		gRes = new GenericResponse(Boolean.TRUE, listSuc);
		json = new JSONSerializer().exclude("*.class").serialize(gRes);
		
		response = new ResponseEntity<String>(json, headers, HttpStatus.OK);
		
		return response;
	}
}
